package com.twan.kotlinbase.app

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jaeger.library.StatusBarUtil
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.twan.kotlinbase.R
import com.twan.kotlinbase.bean.UploadPic
import com.twan.kotlinbase.event.TakePhotoEvent
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.pop.AddPicPopup
import com.twan.kotlinbase.util.GlideUtils
import com.twan.kotlinbase.widgets.MySearchView
import com.umeng.analytics.MobclickAgent
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import me.imid.swipebacklayout.lib.app.SwipeBackActivity
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

//如果你使用databinding,请继承这个基类,用法不变
abstract class BaseDataBindingActivity<T: ViewDataBinding> : SwipeBackActivity() {
    protected var mContext: Activity? = null

    @BindView(R.id.back)
    lateinit var back: ImageButton

    @BindView(R.id.tv_back_text)
    lateinit var tv_back_text: TextView

    @BindView(R.id.ib_right)
    lateinit var ib_right: ImageButton

    @BindView(R.id.title)
    lateinit var title: TextView

    @BindView(R.id.tv_right)
    lateinit var tv_right: TextView

    @JvmField @BindView(R.id.search_view) var searchView: MySearchView? = null
    @JvmField @BindView(R.id.toolbar) var toolbar: Toolbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this,getLayout())
        EventBus.getDefault().register(this)
        StatusBarUtil.setLightMode(this)
        StatusBarUtil.setColor(this, resources.getColor(R.color.head_bg), 0)
        ButterKnife.bind(this)
        mContext = this
        App.addActivity(this)
        initEventAndData()
    }

    @OnClick(R.id.back)
    fun back(view: View?) {
        finish()
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    //物理返回键
    override fun onBackPressed() {
        super.onBackPressed()
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
    }

    fun whiteStatusBar(){
        StatusBarUtil.setColor(this, resources.getColor(R.color.white), 0)
        toolbar?.setBackgroundColor(resources.getColor(R.color.white))
    }

    //白色的toolbar,字体为黑色
    fun whiteToolbar(titleStr:String,rightStr:String=""){
        whiteStatusBar()
        title?.visibility= View.VISIBLE
        title?.text=titleStr
        tv_right?.visibility = View.VISIBLE
        tv_right!!.setTextColor(resources.getColor(R.color.text_black))
        tv_right?.text=rightStr
    }

    @OnClick(R.id.tv_right)
    open fun rightClick(){

    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this);
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this);
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        App.removeActivity(this)
    }

    protected lateinit var mBinding: T
    protected abstract fun getLayout(): Int
    protected abstract fun initEventAndData()



    //处理处理部分
    var mCurrTakePhotoPath = ""
    var uploadType=1 //1相册多选,2视频多选,4案例多选, 3单张
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AddPicPopup.REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) {
            var selected = Matisse.obtainResult(data)
            selected.forEach {
                var realpath = UriUtils.uri2File(it).absolutePath
                LogUtils.e("选择路径: $realpath")
                upload(realpath)
            }
        } else if (requestCode == AddPicPopup.REQUEST_CODE_TAKE_PHOTO && resultCode == Activity.RESULT_OK){
            upload(mCurrTakePhotoPath)
            LogUtils.e("拍照路径: $mCurrTakePhotoPath")
        } else if (requestCode == AddPicPopup.REQUEST_VIDEO_CAPTURE && resultCode == Activity.RESULT_OK) {
            upload(mCurrTakePhotoPath)
            LogUtils.e("视频路径: $mCurrTakePhotoPath")
        }
    }

    //图片选择
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun dataEvent(selected: TakePhotoEvent) {
        mCurrTakePhotoPath = selected.path
        LogUtils.e("拍照或者视频路径:$mCurrTakePhotoPath")
    }

    open fun upload(filepath:String){
        RxHttpScope().launch {
            if (!::loadingPopup.isInitialized) {
                loadingPopup = XPopup.Builder(this@BaseDataBindingActivity).dismissOnTouchOutside(false).asLoading("正在加载中")
            }
            if (loadingPopup.isDismiss) loadingPopup.show()
            var req= RxHttp.postForm("cos/upload").connectTimeout(60000).
            readTimeout(60000).writeTimeout(60000).addFile("file",filepath).toResponse<String>().await()
            if (loadingPopup.isShow) loadingPopup.dismiss()
            uploadCallback(req)
            LogUtils.e("文件上传成功:$req")
        }
    }

    open fun uploadCallback(url:String){

    }






    //图片或者视频多选
    var uploadPics= mutableListOf<UploadPic>().apply { this.add(UploadPic(true)) }
    var uploadVideos= mutableListOf<UploadPic>().apply { this.add(UploadPic(true)) }
    var uploadAnlis= mutableListOf<UploadPic>().apply { this.add(UploadPic(true)) }
    lateinit var loadingPopup: BasePopupView
    /**
     * uploadType2 1相册多选,2视频多选,4案例多选 只传1,2,4
     */
    fun initRvMultiPicOrVideo(recyclerView: RecyclerView, uploadType2:Int=1){
        var datas = if (uploadType2==1) uploadPics else if (uploadType2==2) uploadVideos else uploadAnlis
        recyclerView.layoutManager= GridLayoutManager(this,4)
        recyclerView.adapter=object : BaseQuickAdapter<UploadPic, BaseViewHolder>(R.layout.item_upload_img,datas.asReversed()){
            override fun convert(holder: BaseViewHolder, item: UploadPic) {
                var iv_close=holder.getView<ImageView>(R.id.iv_close)
                var iv_pic=holder.getView<ImageView>(R.id.iv_pic)
                iv_close.visibility=if (item.isAddBtn) View.GONE else View.VISIBLE
                GlideUtils.load(this@BaseDataBindingActivity,iv_pic,item.filepath,if (uploadType2==2) R.mipmap.upload_video else R.mipmap.upload_pic)

                iv_close.setOnClickListener {
                    datas.remove(item)
                    notifyDataSetChanged()
                }
                iv_pic.setOnClickListener {
                    if(!item.isAddBtn) return@setOnClickListener
                    if (datas.size == 10) {
                        ToastUtils.showShort("最多只能选择9张")
                        return@setOnClickListener
                    }
                    uploadType=uploadType2
                    if (uploadType2==1) {
                        XPopup.Builder(this@BaseDataBindingActivity).asCustom(AddPicPopup(this@BaseDataBindingActivity, maxSelect = 10-datas.size)).show()
                    } else if (uploadType2==2){
                        XPopup.Builder(this@BaseDataBindingActivity).asCustom(AddPicPopup(this@BaseDataBindingActivity,maxSelect = 10-datas.size,isTakePhoto = false,mimeType = MimeType.ofVideo())).show()
                    } else if (uploadType2==4){ //案例
                        XPopup.Builder(this@BaseDataBindingActivity).asCustom(AddPicPopup(this@BaseDataBindingActivity, maxSelect = 10-datas.size)).show()
                    }
                }
            }

        }
    }
    //清空图片或者视频的数据
    fun clear(uploadType2:Int=1){
        if (uploadType2==1){
            uploadPics.clear()
            uploadPics.add(UploadPic(true))
        } else if (uploadType2==2) {
            uploadVideos.clear()
            uploadVideos.add(UploadPic(true))
        } else {
            uploadAnlis.clear()
            uploadAnlis.add(UploadPic(true))
        }
    }
    //图片
    fun getPicsUrl():String{
        return getPinjieUrl(uploadPics)
    }
    //视频
    fun getVideosUrl():String{
        return getPinjieUrl(uploadVideos)
    }
    //案例
    fun getAnliUrl():String{
        return getPinjieUrl(uploadAnlis)
    }

    fun getPinjieUrl(datas:MutableList<UploadPic>):String{
        var url=""
        if (datas.size == 1) return ""
        else {
            datas.forEach {
                if (!it.isAddBtn) url += (it.filepath + ",")
            }
        }
        if (url.isNotEmpty() && url.last() == ',') url = url.dropLast(1)
        if (url.isNotEmpty() && url.first() == ',') url = url.drop(1)
        return url
    }
}